package com.sxt.sys.controller;



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxt.pro.Ny_data.xin.HttpClientHelper;
import com.sxt.pro.Ny_data.xin.HttpURLConnectionTest;
import com.sxt.pro.Ny_data.xin.Lilv;
import com.sxt.pro.pojo.AbChina;
import com.sxt.pro.pojo.OutMessage;
import com.sxt.pro.pojo.Sources;
import com.sxt.pro.service.AbChinaService;
import com.sxt.sys.common.ResultObj;
import com.sxt.sys.common.WebUtils;
import com.sxt.sys.domain.BankUser;
import com.sxt.sys.service.BankUserService;

import utils.ResponseWrapper;

/**
 * <p>
 *  登陆前端控制器
 * </p>
 *
 * @author 老雷
 * @since 2019-09-20
 */
@RestController
@RequestMapping("login")
public class LoginController {
	
	//网点用户
	@Autowired
	private BankUserService bankUserService;
	/**  websockegt 发送消息模板 **/
	@Autowired
	private SimpMessagingTemplate template;
	//封装爬取农行数据
	@Autowired
	private AbChinaService abChinaService;
	
	
	
	@RequestMapping("login")
	public ResultObj login(String loginname,String pwd) {
		//security加密验证
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		QueryWrapper<BankUser> queryWrapper=new QueryWrapper<>();
		//查询条件：用户名
		queryWrapper.eq("user_name", loginname);
		//根据登录名查询用户信息
		BankUser bankuser = bankUserService.getOne(queryWrapper);
		
		//登录验证
		if (!StringUtils.isEmpty(bankuser)&& passwordEncoder.matches(pwd, bankuser.getPassword())) {
			//保存用户信息存入session
			WebUtils.getSession().setAttribute("bankuser", bankuser);
			//保存网点用户名存入session
			WebUtils.getSession().setAttribute("username", bankuser.getUsername());
			String username = (String) WebUtils.getSession().getAttribute("username");
			//保存网点编号存入session
			WebUtils.getSession().setAttribute("banknbr", bankuser.getDeptid());
			return ResultObj.LOGIN_SUCCESS;
		} 
		   return ResultObj.LOGIN_ERROR_PASS;	
	}
	
	
	/*********************************************** 银行爬取    接口 *****************************************************/
	
	/**
	 * 每一小时获取农行数据，存入数据库
	 * @return
	 */
	
//    @Scheduled(cron = "0 */1 * * * ?") //每1分钟执行一次
	@Scheduled(cron = "0 0 * * * ?")  
	public void  sendAbChinaDate() {
		try {
			String lilv =this.sendLilvMessage();
			String gold = this.sendGoldMessage();
			String huilv = this.sendHuilv();
			String licai = HttpURLConnectionTest.httpURLConectionGET();
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("lilv", lilv);
	        map.put("gold", gold);
	        map.put("huilv", huilv);
	        AbChina abChina = new AbChina();
	        abChina.setLilv(lilv);
	        abChina.setGold(gold);
	        abChina.setHuilv(huilv);
	        abChina.setLicai(licai);
	        abChina.setCreatetime(new Date());
	        abChinaService.save(abChina);
	        template.convertAndSend("/topic/service_abchina", abChina);
	        System.out.println("爬取利率、汇率、贵金属、理财数据   且推送那——————————————-");
		} catch (Exception e) {
			 e.printStackTrace();
		}
		
		
		 
	}
	
	
	
	/**
	 * 发送最新的数据 ：利率、汇率、贵金属、理财
	 * @return
	 */
	@RequestMapping("/getAbChinaDate")
	@ResponseBody
	public ResponseWrapper  getAbChinaDate() {
		try {
	        AbChina abChina = abChinaService.getNewAbChina();
	        return ResponseWrapper.markSuccess(abChina);
		} catch (Exception e) {
			 e.printStackTrace();
			 return ResponseWrapper.markParamError();
		}
		 
	}	
	
	
	
	/*********************************************** 银行爬取数据封装*****************************************************/

	/**
	 * 发送外汇、贵金属、利率数据
	 * @return
	 */
//	@RequestMapping("/sendThreeData")
//	@ResponseBody
//	public ResponseWrapper  sendNoticeMessage() {
//		try {
//			String lilv =this.sendLilvMessage();
//			String gold = this.sendGoldMessage();
//			String huilv = this.sendHuilv();
//			String licai = HttpURLConnectionTest.httpURLConectionGET();
//	        Map<String, Object> map = new HashMap<String, Object>();
//	        map.put("lilv", lilv);
//	        map.put("gold", gold);
//	        map.put("huilv", huilv);
//	        AbChina abChina = new AbChina();
//	        abChina.setLilv(lilv);
//	        abChina.setGold(gold);
//	        abChina.setHuilv(huilv);
//	        abChina.setLicai(licai);
//	        abChina.setCreatetime(new Date());
//	        abChinaService.save(abChina);
//	        return ResponseWrapper.markSuccess(map);
//		} catch (Exception e) {
//			 e.printStackTrace();
//			 return ResponseWrapper.markParamError();
//		}
//		 
//	}


	//外汇
    public String  sendLilvMessage(){
        String url ="http://www.abchina.com/cn/PersonalServices/Quotation/bwbll/201511/t20151126_807920.htm";
        String nongh = null;
        try {
            nongh = HttpClientHelper.sendGet(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = new byte[0];
        try {
            bytes = nongh.getBytes("ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String s1 = null;
        try {
            s1 = new String(bytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Document document = Jsoup.parse(s1);
        Elements tbody = document.getElementsByTag("tbody");
        String[] split = tbody.text().split(" ");
        List<Lilv> lilvs = new ArrayList<>();
        for (int x=0;x<split.length;x++){
            Lilv lilv = new Lilv();
            if(x%2==0){
                lilv.setPriect(org.apache.commons.lang.StringUtils.strip(split[x]));
                x++;
            }
            lilv.setData(org.apache.commons.lang.StringUtils.strip(split[x]));
            lilvs.add(lilv);
        }

        String s = JSONObject.toJSONString(lilvs);
        return s;
    }

    //贵金属
    public String sendGoldMessage(){
        String url ="http://ewealth.abchina.com/app/data/api/DataService/GoldInfoV2"; 
        String nongh = null;
        try {
            nongh = HttpClientHelper.sendGet(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONArray array = JSONObject.parseObject(nongh).getJSONObject("Data").getJSONArray("Table1");
        int size = array.size();
        for (int x=0;x<size;x++){
            String[] split = array.getJSONObject(x).get("UpdateTime").toString().split(" ");
            //System.out.println("数组长度："+split.length);
            array.getJSONObject(x).put("UpdateTime",split[1]);
        }
        //System.out.println("贵金属："+array);
        return array.toString();
    }
    
    //汇率
    public String sendHuilv(){
        String url ="http://ewealth.abchina.com/app/data/api/DataService/ExchangeRateV2";
        String nongh = null;
        try {
            nongh = HttpClientHelper.sendGet(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONArray array = JSONObject.parseObject(nongh).getJSONObject("Data").getJSONArray("Table");
        int size = array.size();
        for (int x=0;x<size;x++){
            String[] split = array.getJSONObject(x).get("PublishTime").toString().split("T");
            //System.out.println("数组长度："+split[1].split("\\+")[0]);
            array.getJSONObject(x).put("PublishTime",split[1].split("\\+")[0]);
        }
       // System.out.println("汇率："+array);
        return array.toString();
    }
	
	
	
/***************************************************  爬取数据结束*********************************************/	
	
	
	
}

